<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="88px">
      <el-form-item label="设备编码" prop="dev_id">
        <el-input v-model.trim="queryParams.dev_id" placeholder="请输入设备编码" clearable style="width: 220px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="传感器名称" prop="sns_name">
        <el-input v-model.trim="queryParams.sns_name" placeholder="请输入传感器名称" clearable style="width: 220px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="传感器编码" prop="sns_code">
        <el-input v-model.trim="queryParams.sns_code" placeholder="请输入传感器编码" clearable style="width: 220px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="传感器类型" prop="sns_type">
        <el-select v-model="queryParams.sns_type" clearable placeholder="请选择传感器类型" @change="handleQuery"
          style="width: 220px">
          <el-option v-for="item in options2" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="在线状态" prop="online_status">
        <el-select v-model="queryParams.online_status" clearable placeholder="请选择在线状态" @change="handleQuery"
          style="width: 220px">
          <el-option v-for="item in options2_2" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属企业" prop="ent_id">
        <el-select v-model="queryParams.ent_id" clearable placeholder="请选择所属企业" @change="handleQuery"
          style="width: 220px">
          <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
        </el-select>
      </el-form-item>  -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="传感器名称" v-if="columns[0].visible" align="center" width="100">
        <template #default="scope">
          <span :class="{ 'online': scope.row.online_status === 1, 'offline': scope.row.online_status === 0 }">
            {{ scope.row.sns_name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="传感器编码" v-if="columns[1].visible" align="center" width="100">
        <template #default="scope">
          <span :class="{ 'online': scope.row.online_status === 1, 'offline': scope.row.online_status === 0 }">
            {{ scope.row.sns_code }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="传感器类型" v-if="columns[2].visible" prop="sns_show_type" align="center" width="200" />
      <el-table-column label="柜号" v-if="columns[3].visible" prop="cabinet" align="center" width="150" />
      <el-table-column label="所属公司" v-if="columns[4].visible" prop="ent_name" align="center" width="200" />
      <el-table-column label="所属监测站" v-if="columns[5].visible" prop="sta_name" align="center" width="200" />
      <el-table-column label="所属线路" v-if="columns[6].visible" prop="branch_name" align="center" width="200" >
          <template #default="scope">
                <span>{{ scope.row.branch_name || scope.row.master_name }}</span>
          </template>
      </el-table-column>
      <el-table-column label="所属设备" v-if="columns[7].visible" prop="dev_name" align="center" width="250" />
      <el-table-column label="在线状态" v-if="columns[8].visible" align="center" width="100">
        <template #default="scope">
          <span :class="{ 'online': scope.row.online_status === 1, 'offline': scope.row.online_status === 0 }">
            {{ scope.row.online_status === 1 ? '在线' : '离线' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否报警" v-if="columns[9].visible" align="center" width="100">
        <template #default="scope">
          <span>{{ scope.row.offline_alarm_flag==1?'是':'否' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="160px" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Link" @click="handleUpdate2(scope.row)">绑定柜号</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属企业" prop="ent_id" >
          <el-select v-model="form.ent_id" placeholder="请选择所属企业" @change="handleEntChange">
            <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属监测站" prop="station_id" v-if="form.ent_id" >
          <el-select v-model="form.station_id" placeholder="请选择监测站" @change="handleEntChange2">
            <el-option v-for="item in options3" :key="item.id" :label="item.sta_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属线路" prop="line_code" v-if="form.station_id">
          <el-cascader style="width: 600px;" ref="cascaderRef"  :show-all-levels="false"  @change="handleCascaderChange"
           v-model="form.line_code" :options="options4" :props="{ checkStrictly: true,children:'branch_Lines',label:'line_name',value:'line_code'}" />
        </el-form-item> 
        <el-form-item label="开关柜编号" prop="cabinet">
          <el-input v-model.trim="form.cabinet" maxlength="20"  disabled placeholder="和所属线路对应" @input="filterCabinetInput" />
        </el-form-item>
        <el-form-item label="所属设备" prop="dev_id" v-if="form.ent_id" >
          <el-select v-model="form.dev_id" placeholder="请选择所属设备">
            <el-option v-for="item in options5" :key="item.id" :label="item.dev_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="传感器名称" prop="sns_name">
          <el-input v-model.trim="form.sns_name" maxlength="30" placeholder="请输入传感器名称" />
        </el-form-item>
        <el-form-item label="传感器编码" prop="sns_code">
          <el-input v-model.trim="form.sns_code" maxlength="30" placeholder="请输入传感器编码" />
        </el-form-item>
        <el-form-item label="传感器类型" prop="sns_type">
          <el-cascader ref="optCascader" style="width: 470px;" v-model="form.sns_type" :options="optTypes" @change="optTypesChange" />
        </el-form-item>
        <el-form-item label="离线是否报警" label-width="130">
          <el-radio-group v-model="form.offline_alarm_flag">
            <el-radio :value="0">不报警</el-radio>
            <el-radio :value="1">报警</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报警时间间隔" label-width="130" v-if="form.offline_alarm_flag==1">
          <el-select v-model="form.offline_alarm_time" placeholder="请选择时间间隔"  style="width: 240px">
            <el-option v-for="item in options6" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 绑定柜号 -->
    <el-dialog :title="title2" v-model="open2" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef2" :model="form2" :rules="rules2" label-width="180px">
        <el-form-item label="所属线路-(开关柜编号)" prop="cabinet" >
          <el-cascader style="width: 600px;" ref="cascaderRef2" :show-all-levels="false"  @change="handleCascaderChange2"
           v-model="form2.cabinet" :options="options4_2" :props="{ checkStrictly: true,children:'branch_Lines',label:'name',value:'cabinet',emitPath: false}" />
        </el-form-item> 
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm2">确 定</el-button>
          <el-button @click=" open2 = false;">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useInfoStore } from '@/store/modules/info.js'
import { onBeforeMount, onMounted } from 'vue';
import {exportTreeType} from './type.js'

const userInfo = useInfoStore();

const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");


const dataList = ref([]);
const open = ref(false);
const open2 = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const menuRef = ref(null);
const options1 = ref([]);
const options2 = ref([
  { id: '01', name: '零序电流采集器' },
  { id: '02', name: '过电压保护器' },
  { id: '03', name: '温度采集器' },
  { id: '04', name: '电机' },
]);
const options2_2 = ref([
  { id: 1, name: '在线' },
  { id: 0, name: '离线' },
]);
const options3 = ref([]); //监测站点
const options4 = ref([]); //线路列表
const options4_2 = ref([]); //线路列表
const options5 = ref([]); //设备列表
const cascaderRef = ref(null);
const cascaderRef2 = ref(null);
const options6 = [
  { value: 1, label: '1分钟' },
  { value: 2, label: '2分钟' },
  { value: 5, label: '5分钟' },
  { value: 10, label: '10分钟' },
  { value: 30, label: '30分钟' },
]
// 列显隐信息
const columns = ref([
  { key: 0, label: `传感器名称`, visible: true },
  { key: 1, label: `传感器编码`, visible: true },
  { key: 2, label: `传感器类型`, visible: true },
  { key: 3, label: `柜号`, visible: true },
  { key: 4, label: `所属公司`, visible: false },
  { key: 5, label: `所属监测站`, visible: false },
  { key: 6, label: `所属线路`, visible: true },
  { key: 7, label: `所属设备`, visible: true },
  { key: 8, label: `在线状态`, visible: true },
  { key: 9, label: `是否报警`, visible: false },
]);
const data = reactive({
  form: {
    id: null,
    ent_id: null,//企业ID
    sns_name: null,//传感器名称
    sns_code: null,//传感器编号
    sns_type: null,//传感器编号
    sns_show_type: null,//传感器类型名称
    position: null,//位置
    offline_alarm_flag: 0,//离线是否报警 0-不报警；1-报警
    offline_alarm_time: 5,//离线报警时间间隔，单位分钟，默认0为无间隔
    station_id:null,//监测站ID
    branch_id:null,//线路ID
    master_id:null,//母线 线路ID
    dev_id:null,//设备ID
    state: 1,//是否停用
    cabinet:null,//开关柜编号
    line_code:null,//线路编码
  },
  form2: {
    id: null,
    cabinet:null,//开关柜编号
    branch_id:null,//线路编码
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    ent_id: null,//企业ID
    station_id: null,//监测站点ID
    dev_model: null,//设备型号
    dev_id: null,//设备编码
    dev_name: null,//设备名称
    state: null,//是否停用
    dev_id:null,//设备ID
    online_status:null,//在线状态
  },
  rules: {
    ent_id: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    sns_name: [{ required: true, message: "传感器名称不能为空", trigger: "blur" }],
    sns_code: [{ required: true, message: "传感器编码不能为空", trigger: "blur" }],
    sns_type: [{ required: true, message: "传感器类型不能为空", trigger: "blur" }],
    station_id: [{ required: true, message: "请选择监测站", trigger: "blur" }],
    line_code: [{ required: true, message: "请选择线路", trigger: "blur" }],
    dev_id: [{ required: true, message: "请选择设备", trigger: "blur" }],
  },
  rules2: {
    cabinet: [{ required: true, message: "请选择需要绑定的柜号", trigger: "blur" }],
  },
});

const optTypes = exportTreeType;
const optCascader = ref(null);

const { queryParams, form, form2, rules,rules2 } = toRefs(data);

// 自定义校验函数
const validateTypeOrSpec = (rule, value, callback) => {
  if (!form.value.types && !form.value.specifications) {
    callback(new Error('型号和规格至少输入一项'));
  } else {
    callback();
  }
};
// 更新校验规则
rules.value.types = { validator: validateTypeOrSpec, trigger: 'blur' };
rules.value.specifications = { validator: validateTypeOrSpec, trigger: 'blur' };

onMounted(() => {
  if(route.query.dev_code){
    queryParams.value.dev_id = route.query.dev_code;
    showSearch.value = false;
  }
  getGetEnterpriseList();
  getList();
})


// 过滤输入内容，只保留字母和数字
function filterCabinetInput(e) {
  // 使用正则表达式替换非字母和数字的字符
  form.value.cabinet = e.replace(/[^a-zA-Z0-9]/g, '');
}

// 更新校验规则
rules.value.cabinet = [
  { required: true, message: "开关柜编号不能为空", trigger: "blur" },
  { pattern: /^[a-zA-Z0-9]+$/, message: "只能输入字母或数字", trigger: "blur" }
];

// 树结构选中
function optTypesChange(value) {
  form.value.sns_show_type = optCascader.value.getCheckedNodes()[0].text;
  // let str = arr.pathLabels.join('——');
  // form.value.sns_show_type = str;
}
/** 1.查询企业列表下拉 */
function getGetEnterpriseList() {
  proxy.cloudTv_API.GetEnterpriseList({}).then(response => {
    if (response.data) {
      options1.value = response.data || [];
    }
  });
}
//2.获取监测站 -- 企业下拉
function handleEntChange(value,init=true) {
  if(init){
    form.value.line_code = null; //选中监测站 清空支线
    form.value.master_id = null; //选中监测站 清空支线
    form.value.branch_id = null;
  }
  proxy.cloudTv_API.GetStationList({
    enterpriseID: value,
  }).then(response => {
    if (response.data?.length > 0) {
      options3.value = response.data || [];
      options3.value.forEach(item => {
        item.sta_name = item.staName;
      });
      if(!form.value.station_id){ //如果监测站无值，则默认第一条
         form.value.station_id = options3.value[0].id;
      }
      getLineList(form.value.station_id); //
    }else{
      form.value.station_id = null;
      options3.value =  [];
      form.value.line_id = null;
      options4.value =  [];
      proxy.$modal.msgError("当前企业还没有添加监测站~");
    }
  });
  // 设备列表
  proxy.cloudTv_API.GetDeviceList({
    ent_id: value,
  }).then(response => {
    if (response.data?.length > 0) {
      options5.value = response.data || [];
      if(!form.value.dev_id){ //如果设备无值，则默认第一条
         form.value.dev_id = options5.value[0].id;
      }
    }else{
      form.value.dev_id = null;
      options5.value =  [];
      proxy.$modal.msgError("当前企业还没有设备~");
    }
  });
}

//3.获取监测--母线-支线
function getLineList(value) {
  proxy.cloudTv_API.GetMasterLineList({
    stationID: value,
    state: 1,
  }).then(response => {
    if (response.data?.length > 0) {
        // 为第一层父级节点添加 disabled 属性
      const processedData = response.data.map(item => processLineData(item));
      options4.value = processedData || [];
      if(!form.value.line_code){ //如果线路无值，则默认第一条
          // form.value.line_code = options4.value[0].line_code;
          // form.value.master_id = options4.value[0].id; //默认选中母线
          // form.value.branch_id = 0;
        }
      }else{
        form.value.line_code = null;
        form.value.master_id = null;
        form.value.branch_id = null;
        options4.value =  [];
        proxy.$modal.msgError("当前监测站还没有线路~");
      }
  });
}

function handleEntChange2(value) {
  form.value.line_code = null; //选中监测站 清空支线
  form.value.master_id = null; //选中监测站 清空支线
  form.value.branch_id = null;
  getLineList(value);
}
  // 主动关闭弹层
function handleCascaderChange(e) {
    // 获取当前选中的节点列表
  const item = cascaderRef.value.getCheckedNodes()[0].data;
  if(item?.master_LineID){ //选中支线
    form.value.master_id = item.master_LineID;
    form.value.branch_id = item.id;
    form.value.cabinet = item.cabinet;
  }else{//选中母线
    // form.value.master_id = item.id;
    form.value.branch_id = 0;
  }
  cascaderRef.value.togglePopperVisible(false)
}
  // 主动关闭弹层
function handleCascaderChange2(e) {
    // 获取当前选中的节点列表
  const item = cascaderRef2.value.getCheckedNodes()[0].data;
  form2.value.branch_id = item.id;
  console.log(form2.value);
  cascaderRef2.value.togglePopperVisible(false)
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetSenserPageList(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除传感器名称"' + row.sns_name + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelSenser({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}


/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    id: null,
    ent_id: null,//企业ID
    sns_name: null,//传感器名称
    sns_code: null,//传感器编号
    sns_type: null,//传感器编号
    sns_show_type: null,//传感器类型名称
    position: null,//位置
    offline_alarm_flag: 0,//离线是否报警 0-不报警；1-报警
    offline_alarm_time: 5,//离线报警时间间隔，单位分钟，默认0为无间隔
    station_id:null,//监测站ID
    branch_id:null,//线路ID
    master_id:null,//母线 线路ID
    dev_id:null,//设备ID
    line_code:null,//线路编码
    state: 1,//是否停用
    cabinet:null,//开关柜编号
  };
}
/** 新增物料 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增传感器";
}

/** 修改物料 */
function handleUpdate(row) {
  let newRow = JSON.parse(JSON.stringify(row));
  reset();
  Object.keys(form.value).forEach(key => {
    form.value[key] = newRow[key];
  });
  // 如果支线有 优先回显 展示支线
  form.value.line_code = newRow.bline_code;
  form.value.master_id = newRow.master_id;
  form.value.branch_id = newRow.branch_id;
  form.value.station_id = newRow.sta_id;
  open.value = true;
  title.value = "修改传感器";
  handleEntChange(newRow.ent_id,false);//获取监测站
}

/** 绑定柜号 */
function handleUpdate2(row) {
  proxy.cloudTv_API.GetMasterLineList({
    stationID: row.sta_id,
    state: 1,
  }).then(response => {
    if (response.data?.length > 0) {
      const processedData = response.data.map(item => processLineData(item));
      form2.value.id = row.id;
      form2.value.cabinet = row.cabinet;
      options4_2.value = processedData || [];
      open2.value = true;
      title2.value = "绑定柜号";
    }
  });
}

/**
 * 递归处理线路数据，拼接 name 属性
 * @param {Object} item 线路数据项
 * @param {boolean} isFirstLevel 是否为第一层数据，默认为 true
 * @returns {Object} 处理后的线路数据项
 */
 function processLineData(item, isFirstLevel = true) {
  // 根据是否为第一层决定是否添加 disabled 属性
  const newItem = isFirstLevel ? { ...item, disabled: true } : { ...item }; 
  // 拼接 name 属性
  newItem.name = item.cabinet ? `${item.line_name}-(${item.cabinet})` : item.line_name;
  newItem.line_name = item.cabinet ? `${item.line_name}-(${item.cabinet})` : item.line_name;
  if (item.branch_Lines && item.branch_Lines.length > 0) {
    // 递归处理子项时，标记非第一层
    newItem.branch_Lines = item.branch_Lines.map(subItem => processLineData(subItem, false)); 
  }
  return newItem;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.EditSenser({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddSenser({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 提交按钮 */
function submitForm2() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
        // proxy.cloudTv_API.EditSenser({
        //   ...form.value,
        // }).then(response => {
        //   proxy.$modal.msgSuccess("绑定成功");
        //   open.value = false;
        //   getList();
        // });
    }
  });
}

// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
}

.online {
  color: #67C23A;
}

.offline {
  color: #F56C6C;
}
</style>